﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Kooboo.CMS.Sites;
using Kooboo.CMS.DataModule.Models;
using Kooboo.CMS.DataModule.Services;

namespace Kooboo.CMS.DataModule.Areas.DataModule.Controllers
{
    public class ImportController : AreaControllerBase
    {
        private ImportService _importService;

        public ImportController() :
            this(new ImportService())
        { }

        public ImportController(ImportService importService)
        {
            _importService = importService;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(ImportModel model)
        {
            JsonResultEntry result = new JsonResultEntry(ModelState);

            try
            {
                if(ModelState.IsValid)
                {
                    _importService.ImportData(model, Request.Files["DataFile"].InputStream);
                }
            }
            catch(Exception e)
            {
                result.AddException(e);
            }

            return Json(result);
        }

        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            if(string.IsNullOrEmpty(contentType))
            {
                if(Request.ContentType.Contains("multipart/form-data;"))
                {
                    contentType = "text/plain";
                }
            }
            return base.Json(data, contentType, contentEncoding, behavior);
        }
    }
}